package com.liang.lessonIp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TaskReceive implements Runnable{
  DatagramSocket socket= null;
    private int port;
    private String msgFrom;

    public TaskReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
          socket =   new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            //准备接收包裹
            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);//阻塞式接收包裹

                //断开连接 bye
                byte[] data = packet.getData();
                String s = new String(data, 0, data.length);
                System.out.println(s);

                System.out.println(msgFrom+s);

                if (s.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        socket.close();
    }
}
